<?php
namespace app\middleware;

use app\service\LogService;
use think\Request;

class OperateLog
{
    public function handle(Request $request, \Closure $next)
    {
        $response = $next($request);
        
        try {
            $userInfo = $request->userInfo; // 从JWT中间件获取的用户信息
            $path = $request->pathinfo();
            
            // 解析操作类型和模块
            $operation = $this->getOperation($path, $request->method());
            
            // 记录日志
            LogService::record(
                $userInfo['id'] ?? 0,
                $operation['type'],
                $operation['module'],
                $request->ip(),
                $request->param(),
                $response->getCode() === 200,
                $response->getData()['msg'] ?? '',
                $request->method(),
                $path
            );
        } catch (\Exception $e) {
            // 日志记录失败不应影响主流程
        }

        return $response;
    }

    private function getOperation($path, $method)
    {
        $map = [
            'auth/login'    => ['type' => '登录', 'module' => '认证'],
            'auth/logout'   => ['type' => '退出', 'module' => '认证'],
            'user/add'      => ['type' => '新增用户', 'module' => '用户管理'],
            'user/edit'     => ['type' => '修改用户', 'module' => '用户管理'],
            'user/delete'   => ['type' => '删除用户', 'module' => '用户管理'],
            'device/add'    => ['type' => '新增设备', 'module' => '设备管理'],
            'device/edit'   => ['type' => '修改设备', 'module' => '设备管理'],
            'device/delete' => ['type' => '删除设备', 'module' => '设备管理'],
            'role/add'      => ['type' => '新增角色', 'module' => '权限管理'],
            'role/edit'     => ['type' => '修改角色', 'module' => '权限管理'],
            'role/delete'   => ['type' => '删除角色', 'module' => '权限管理'],
            'permission/add' => ['type' => '新增权限', 'module' => '权限管理'],
            'permission/edit' => ['type' => '修改权限', 'module' => '权限管理'],
            'permission/delete' => ['type' => '删除权限', 'module' => '权限管理']
        ];

        return $map[$path] ?? ['type' => $method, 'module' => '系统'];
    }
}
